#include<bits/stdc++.h>

using namespace std;
struct picture {
    string name;
    string hash;
} a[12000];
int n;

int find(string b) {
    int sum, Max = -1;
    for (int i = 0; i < n; i++) {
        sum = 0;
        for (int j = 0; j < 36; j++) {
            if ( b[j] == a[i].hash[j] ) sum++;
        }
        Max = max(Max, sum);
    }
    return Max;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> a[i].name >> a[i].hash;
    }
    int t;
    cin >> t;
    while (t--) {
        string Name, Hash;
        cin >> Name >> Hash;
        int flag = find(Hash);
        string s[1000];
        int k = 0, sum;
        for (int i = 0; i < n; i++) {
            sum = 0;
            for (int j = 0; j < 36; j++) {
                if ( Hash[j] == a[i].hash[j] ) sum++;
            }
            if ( sum == flag )s[k++] = a[i].name;
        }
        cout << k << "\n" << flag << "\n";
        for (int i = 0; i < k; i++) {
            cout << s[i] << endl;
        }
    }

    return 0;
}